package com.example.yiwei.crm.view.activity.clueActivity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.clueDao;
import com.example.yiwei.crm.dao.customerDao;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetClue;
import com.example.yiwei.crm.data.GetClueData;
import com.example.yiwei.crm.dao_impl.clueDaoImpl;
import com.example.yiwei.crm.dao_impl.customerDaoImpl;
import com.example.yiwei.crm.entity.ClueMeesageEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.view.Class.getSpinnerClass;
import com.example.yiwei.crm.view.activity.customerActivity.CustomerAddMessageActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

public class ClueAddMessageActivity extends AppCompatActivity {
private EditText edit_clue_name,edit_disease,edit_contact,edit_mobile_phone,
        edit_next_content,edit_addtional;
    private Spinner spinner_channel_source,spinner_channel_class,spinner_department,
            spinner_disease,spinner_manager;
    private TextView txt_next_time;
    private TimePickerView mpv;
    private TimePickerView nmpv;
    String NEXT_TIME;
    Button btn_next_time;
    ImageView img_commit,img_back;
    private RadioGroup rg_sex;
    private RadioButton rb_men,rb_women;
    List<Map<String,String>> clueSpinner1;
    List<Map<String,String>> clueSpinner2;
    List<Map<String,String>> clueSpinner3;
    List<Map<String,String>> clueSpinner4;
    List<String> departmen_list,qdfl_list,QDLY_list,disease_list;
    private ArrayAdapter adapter1,adapter2,adapter3,adapter4,adapter6;
    private String channel_classification,channel_source,department,disease_class, managerName;
    private String result;
    int ID1, ID2, ID3,ID4,manager_id;
    ClueMeesageEntity clue;
    private TextView txt_title;
    int sex;
    private RelativeLayout relativeLayout;
    List<managerEntity> managerList;
    List<String>name_list=new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clue_add_message);
        relativeLayout= (RelativeLayout) findViewById(R.id.clue_add_relative_manager);
        btn_next_time= (Button) findViewById(R.id.clue_add_btn_next_time);
        img_back= (ImageView) findViewById(R.id.clue_add__img_back);
        img_commit= (ImageView) findViewById(R.id.clue_add_img_commit);
        txt_next_time= (TextView) findViewById(R.id.clue_add_txt_next_time);
        edit_addtional= (EditText) findViewById(R.id.clue_add_edit_addtional);
        edit_clue_name= (EditText) findViewById(R.id.clue_add_edit_name);
        edit_contact= (EditText) findViewById(R.id.clue_add_edit_contact);
        edit_mobile_phone= (EditText) findViewById(R.id.clue_add_edit_mobile_phone);
        edit_next_content= (EditText) findViewById(R.id.clue_add_edit_next_content);
        spinner_channel_class= (Spinner) findViewById(R.id.clue_add_spinner_channel_class);
        spinner_channel_source= (Spinner) findViewById(R.id.clue_add_spinner_channel_source);
        spinner_department= (Spinner) findViewById(R.id.clue_add_spinner_department);
        spinner_disease= (Spinner) findViewById(R.id.clue_add_spinner_disease_class);
        spinner_manager= (Spinner) findViewById(R.id.clue_add_spinner_manager);
        txt_title= (TextView) findViewById(R.id.clue_add_txt_title);
        rg_sex= (RadioGroup) findViewById(R.id.clue_add_base_sex);
        rb_men= (RadioButton) findViewById(R.id.clue_add_base_men);
        rb_women= (RadioButton) findViewById(R.id.clue_add_base_women);
//判断选择的性别是什么
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i==rb_men.getId()){
                    sex=1;
                }else{
                    sex=2;
                }
            }
        });
        if (getIntent().getStringExtra("tag")!=null) {
            if ("update".equals(getIntent().getStringExtra("tag"))) {
                txt_title.setText("修改线索");
            }
        }
        if ("xiansuochi".equals(getIntent().getStringExtra("xiansuochiTag"))){
            relativeLayout.setVisibility(View.GONE);
        }
        //获取实体类的值
        clue= GetClue.get();
        //创建选择器
        nmpv = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置时间范围
        Calendar calendar = Calendar.getInstance();
        nmpv.setRange(calendar.get(Calendar.YEAR) - 100, calendar.get(Calendar.YEAR) + 100);
        //插入时间
        nmpv.setTime(new Date());
        btn_next_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                nmpv.show();
            }
        });
        //选择监听
        nmpv.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                NEXT_TIME=getTime(date);
                txt_next_time.setText(NEXT_TIME);
            }
        });

        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                add();
            }
        });
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
     new Thread(new Runnable() {
         @Override
         public void run() {
             final customerDao customer=new customerDaoImpl();
             result = getSpinnerClass.getSpinner();
             //部门
             clueSpinner1=customer.querySpinnerContent(result,7);
             //渠道分类
             clueSpinner2=customer.querySpinnerContent(result,4);
             //渠道来源
             clueSpinner3=customer.querySpinnerContent(result,5);
             //疾病种类
             clueSpinner4=customer.querySpinnerContent(result,3);
             runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     qdfl_list= new ArrayList<>();
                     qdfl_list.add(0,"");
                     for (int i2=0;i2<clueSpinner2.size();i2++){
                         qdfl_list.add( clueSpinner2.get(i2).get("QDFL02"));
                     }
                     adapter2 = new ArrayAdapter(ClueAddMessageActivity.this,android.R.layout.simple_spinner_item, qdfl_list);
                     spinner_channel_class.setAdapter(adapter2);
                     spinner_channel_class.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                         @Override
                         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                             channel_classification=spinner_channel_class.getSelectedItem().toString();
                             for (int i = 0;i<clueSpinner2.size();i++){
                                 if (channel_classification.equals(clueSpinner2.get(i).get("QDFL02"))){
                                     ID2 = Integer.valueOf(clueSpinner2.get(i).get("QDFL01"));
                                 }
                             }

                         }

                         @Override
                         public void onNothingSelected(AdapterView<?> parent) {

                         }
                     });
                     QDLY_list= new ArrayList<>();
                     QDLY_list.add(0,"");
                     for (int i2=0;i2<clueSpinner3.size();i2++){
                         QDLY_list.add( clueSpinner3.get(i2).get("QDLY02"));
                     }
                     adapter3 = new ArrayAdapter(ClueAddMessageActivity.this,android.R.layout.simple_spinner_item, QDLY_list);
                     spinner_channel_source.setAdapter(adapter3);
                     spinner_channel_source.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                         @Override
                         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                             channel_source=spinner_channel_source.getSelectedItem().toString();
                             for (int i = 0;i<clueSpinner3.size();i++){
                                 if (channel_source.equals(clueSpinner3.get(i).get("QDLY02"))){
                                     ID3 = Integer.valueOf(clueSpinner3.get(i).get("QDLY01"));
                                 }
                             }

                         }
                         @Override
                         public void onNothingSelected(AdapterView<?> parent) {

                         }
                     });
                     departmen_list= new ArrayList<>();
                     departmen_list.add(0,"");
                     for (int i2=0;i2<clueSpinner1.size();i2++){
                         departmen_list.add( clueSpinner1.get(i2).get("BM02"));
                     }
                     adapter1= new ArrayAdapter(ClueAddMessageActivity.this,android.R.layout.simple_spinner_item, departmen_list);
                     spinner_department.setAdapter(adapter1);
                     spinner_department.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                         @Override
                         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                             department=spinner_department.getSelectedItem().toString();
                             for (int i = 0;i<clueSpinner1.size();i++){
                                 if (department.equals(clueSpinner1.get(i).get("BM02"))){
                                     ID1 = Integer.valueOf(clueSpinner1.get(i).get("BM01"));
                                 }
                             }

                         }
                         @Override
                         public void onNothingSelected(AdapterView<?> parent) {

                         }
                     });
                     disease_list= new ArrayList<>();
                     disease_list.add(0,"");
                     for (int i2=0;i2<clueSpinner4.size();i2++){
                         disease_list.add( clueSpinner4.get(i2).get("BGLX02"));
                     }
                     adapter4= new ArrayAdapter(ClueAddMessageActivity.this,android.R.layout.simple_spinner_item, disease_list);
                     spinner_disease.setAdapter(adapter4);
                     spinner_disease.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                         @Override
                         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                             disease_class=spinner_disease.getSelectedItem().toString();
                             for (int i = 0;i<clueSpinner4.size();i++){
                                 if (disease_class.equals(clueSpinner4.get(i).get("BGLX02"))){
                                     ID4 = Integer.valueOf(clueSpinner4.get(i).get("BGLX01"));
                                 }
                             }

                         }
                         @Override
                         public void onNothingSelected(AdapterView<?> parent) {

                         }

                     });
                     new Thread(new Runnable() {
                         @Override
                         public void run() {
                             managerDao manaDao=new managerDaoImpl();
                             managerList=manaDao.queryAllManager(baseClass.query_manager_url,null);
                             name_list.add(0,"");
                             for (int i2=0;i2<managerList.size();i2++){
                                 name_list.add( managerList.get(i2).getManager_name());
                             }
                             runOnUiThread(new Runnable() {
                                 @Override
                                 public void run() {
                                     adapter6 = new ArrayAdapter(ClueAddMessageActivity.this,android.R.layout.simple_spinner_item, name_list);
                                     spinner_manager.setAdapter(adapter6);
                                     spinner_manager.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                         @Override
                                         public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                             managerName=spinner_manager.getSelectedItem().toString();
                                             for (int i = 0;i<managerList.size();i++){
                                                 if (managerName.equals(managerList.get(i).getManager_name())){
                                                     manager_id = Integer.valueOf(managerList.get(i).getManager_id());
                                                 }
                                             }


                                         }
                                         @Override
                                         public void onNothingSelected(AdapterView<?> parent) {

                                         }
                                     });
                                     if (getIntent().getStringExtra("tag")!=null) {
                                         if ("update".equals(getIntent().getStringExtra("tag"))) {
                                             setdata();
                                         }
                                     }
                                 }
                             });
                         }
                     }).start();

                    }
             });
         }
     }).start();

    }
    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
    public void setdata(){
        edit_clue_name.setText(clue.getClue_name());
        if(clue.getClue_gender()==1){
            rb_men.setChecked(true);
        }else if (clue.getClue_gender()==2){
            rb_women.setChecked(true);
        }
        //疾病种类
        String disease = "";
        SpinnerAdapter adapter1 = spinner_disease.getAdapter();
        for (int i = 0;i<clueSpinner4.size();i++){
            if (clue.getClue_disease_category_id()==Integer.valueOf(clueSpinner4.get(i).get("BGLX01"))){
                disease= clueSpinner4.get(i).get("BGLX02");

            }
        }
        for (int i =0;i<adapter1.getCount();i++){
            if (disease.equals(adapter1.getItem(i).toString())){
                spinner_disease.setSelection(i);
            }
        }
        //渠道来源
        String channel_source = "";
        SpinnerAdapter adapter2 = spinner_channel_source.getAdapter();
        for (int i = 0;i<clueSpinner3.size();i++){
            if (clue.getClue_channel_source_id()==Integer.valueOf(clueSpinner3.get(i).get("QDLY01"))){
                channel_source= clueSpinner3.get(i).get("QDLY02");

            }
        }
        for (int i =0;i<adapter2.getCount();i++){
            if (channel_source.equals(adapter2.getItem(i).toString())){
                spinner_channel_source.setSelection(i);

            }
        }
        //渠道分类
        String channel_class = "";
        SpinnerAdapter adapter3 = spinner_channel_class.getAdapter();
        for (int i = 0;i<clueSpinner2.size();i++){
            if (clue.getClue_channel_classification_id()==Integer.valueOf(clueSpinner2.get(i).get("QDFL01"))){
                channel_class= clueSpinner2.get(i).get("QDFL02");
            }
        }
        for (int i =0;i<adapter3.getCount();i++){
            if (channel_class.equals(adapter3.getItem(i).toString())){
                spinner_channel_class.setSelection(i);


            }
        }
        //所属部门
        String department = "";
        SpinnerAdapter adapter4 = spinner_department.getAdapter();
        for (int i = 0;i<clueSpinner1.size();i++){
            if (clue.getClue_department_id()==Integer.valueOf(clueSpinner1.get(i).get("BM01"))){
                department= clueSpinner1.get(i).get("BM02");
            }
        }
        for (int i =0;i<adapter4.getCount();i++){
            if (department.equals(adapter4.getItem(i).toString())){
                spinner_department.setSelection(i);

            }
        }
        edit_contact.setText(clue.getClue_contact());
        edit_mobile_phone.setText(clue.getClue_mobile_phone());
        edit_next_content.setText(clue.getClue_next_content());
        if (clue.getClue_next_time()!=null&&!clue.getClue_next_time().equals("")) {
            boolean b = clue.getClue_next_time().matches("\\d{4}-\\d{2}-\\d{2}");
            if (b) {
                txt_next_time.setText(clue.getClue_next_time());
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                String next_time = clue.getClue_next_time();
                long l = Long.parseLong(next_time);
                Date date = new Date(l);
                String nTime = sdf.format(date);
                txt_next_time.setText(nTime);
            }
        }
        edit_addtional.setText(clue.getClue_additional());
        SpinnerAdapter spadapter6 = spinner_manager.getAdapter();
        String names=clue.getClue_manager_name();
        if (names!=null){
            for (int i = 0;i<spadapter6.getCount();i++){
                if (names.equals(spadapter6.getItem(i).toString())){
                    spinner_manager.setSelection(i);
                }
            }
        }
    }
    //上传至服务器
    public void add(){
       new Thread(new Runnable() {
           @Override
           public void run() {
               String str;
               String results="";
               JSONObject object=new JSONObject();
               try {
                   object.put("XAA02",manager_id);
                   object.put("XAA03",edit_clue_name.getText().toString());
                   object.put("XAA04",sex);
                   object.put("AKB01",ID4);
                   object.put("XAA06",edit_contact.getText().toString());
                   object.put("XAA08",edit_mobile_phone.getText().toString());
                   object.put("AKD01",ID3);
                   object.put("AKC01",ID2);
                   object.put("XAA13",ID1);
                   object.put("XAA14",txt_next_time.getText().toString());
                   object.put("XAA15",edit_next_content.getText().toString());
                   object.put("XAA16",edit_addtional.getText().toString());

               } catch (JSONException e) {
                   e.printStackTrace();
               }
               if (getIntent().getStringExtra("tag")!=null) {
                   if ("update".equals(getIntent().getStringExtra("tag"))) {
                       try {
                           object.put("XAA01",clue.getClue_id());
                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
                       //修改需要多上传一个id
                        str=object.toString();
                        results=NetWorkUtils.getCount(baseClass.update_clue_message_url,str);
                   }
               }else {
                   str = object.toString();
                   results = NetWorkUtils.getCount(baseClass.add_clue_message_url, str);
               }
               try {
                   JSONObject json=new JSONObject(results);
                   String BOOLEN=json.getString("boolean");
                   if ("success".equals(BOOLEN)){
                       List<ClueMeesageEntity> clueMeesageEntities;
                       clueDao clueDao=new clueDaoImpl();
                       if ("xiansuochi".equals(getIntent().getStringExtra("xiansuochiTag"))){
                            clueMeesageEntities=clueDao.querySimpleClueMessage(baseClass.clue_group_url,null);
                       }else {
                            clueMeesageEntities = clueDao.querySimpleClueMessage(baseClass.query_all_clue_message_ul, null);
                       }
                       GetClueData.CreateData();
                       GetClueData.clue=clueMeesageEntities;
                       if (GetClueData.clue!=null) {
                           if ("update".equals(getIntent().getStringExtra("tag"))) {
                               setData();
                               finish();
                           } else {
                               finish();
                           }
                       }

                   }else{
                       Log.d("boolean",BOOLEN);
                   }
               } catch (JSONException e) {
                   e.printStackTrace();
               }

           }
       }) .start();
    }
    public void setData(){
        clue.setClue_manager(manager_id);
        clue.setClue_manager_name(managerName);
        clue.setClue_name(edit_clue_name.getText().toString());
        clue.setClue_gender(sex);
        clue.setClue_department_id(ID1);
        clue.setClue_department(department);
        clue.setClue_channel_classification_id(ID2);
        clue.setClue_channel_classification(channel_classification);
        clue.setClue_channel_source_id(ID3);
        clue.setClue_channel_source(channel_source);
        clue.setClue_disease_category_id(ID4);
        clue.setClue_disease_category(disease_class);
        clue.setClue_contact(edit_contact.getText().toString());
        clue.setClue_mobile_phone(edit_mobile_phone.getText().toString());
        clue.setClue_next_time(txt_next_time.getText().toString());
        clue.setClue_next_content(edit_next_content.getText().toString());
        clue.setClue_additional(edit_addtional.getText().toString());
    }
}
